package com.cqeec.demo.util;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Cookie处理工具类
 * 
 * @Title: CookieUtil
 * @Descripton: 对客户端Cookie对象进行操作
 */
public class CookieUtil {
	/**
	 * 添加客户端Cookie对象
	 * 
	 * @param response     响应对象
	 * @param cookieName   cookie名字
	 * @param cookieValue  cookie值
	 * @param maxAge       cookie生命周期 以秒为单位
	 */
	public static void addCookie(HttpServletResponse response, String cookieName, String cookieValue, int maxAge) {
		Cookie cookie = new Cookie(cookieName, cookieValue);
		
		cookie.setPath("/");
		if (maxAge > 0) {
			cookie.setMaxAge(maxAge);
		}
		
		response.addCookie(cookie);
	}

	/**
	 * 根据名字获取Cookie对象
	 * 
	 * @param request     请求对象
	 * @param cookieName  cookie名字
	 * @return 返回指定名称的Cookie字符串
	 */
	public static String getCookieByName(HttpServletRequest request, String cookieName) {
		Map<String, Cookie> cookieMap = readCookieMap(request);
		
		if (cookieMap.containsKey(cookieName)) {
			Cookie cookie = (Cookie) cookieMap.get(cookieName);
			
			return cookie.getValue();
		} else {
			return null;
		}
	}

	/**
	 * 获取客户端所有Cookie对象并封装到Map集合中
	 * 
	 * @param request 请求对象
	 * @return
	 */
	private static Map<String, Cookie> readCookieMap(HttpServletRequest request) {
		Map<String, Cookie> cookieMap = new HashMap<String, Cookie>(0);
		cookieMap.clear();
		
		Cookie[] cookies = request.getCookies();
		if (null != cookies) {
			for (Cookie cookie : cookies) {
				cookieMap.put(cookie.getName(), cookie);
			}
		}
		
		return cookieMap;
	}
	
}
